import time

from py.day15.客户信息管理系统02.customer import Customer


class CMS:
    def __init__(self):
        self.customer_id_dict = {}  # k ：id  v:customer
        self.customer_name_dict = {}  # k:name  v:(k :id  v:customer)

    # --------------------------------输入客户,id 校验------------------------------------------
    def set_customer_id(self):
        """输入客户id,id 校验"""
        customer_id = "None"
        for i in range(3):
            if i < 2:
                customer_id = input("请输入用户id；")
                if Customer.check_c_id(customer_id):
                    print(customer_id)
                    break
                else:
                    print("id 必须是纯数字！")
            else:
                customer_id = input("这是最后一的机会，请好好把握，请输入用户id；")

                if Customer.check_c_id(customer_id):
                    print(customer_id)
                    break
                else:
                    print("3次机会用完了，终止添加客户！")

        if customer_id in self.customer_id_dict:
            print("客户id已存在，终止添加客户")
            return False
        else:
            return customer_id

    # ----------------------------------------------输入客户name 校验-----------------------------------------------------------
    def set_customer_name(self):
        """输入客户,name校验"""
        customer_name = "None"
        for i in range(3):
            if i < 2:
                customer_name = input("请输入用户name；")
                if Customer.check_name(customer_name):
                    print(customer_name)
                    break
                else:
                    print("name必须是纯字母！请重新输入：")
            else:
                customer_name = input("这是最后一的机会，请好好把握,请重新输入用户名字；")

                if Customer.check_name(customer_name):
                    print(customer_name)
                    break
                else:
                    print("3次机会用完了，终止添加客户名字！")
                    return False
        return customer_name

    # ----------------------------------------------输入客户, age 校验-----------------------------------------------------------

    def set_customer_age(self):
        customer_age = input("请输入你的年龄：")
        if Customer.check_age(customer_age):
            return customer_age
        else:
            print("输入的age不合理，使用默认的")
        return "None"  # 这里要写返回值，不写的话， 这里默认返回的 是None 会覆盖掉初始化设置的默认的“None”，会报错

    # ----------------------------------------------添加客户, phone 校验-----------------------------------------------------------

    def set_customer_phone(self):
        customer_phone = input("请输入你的电话：")
        if Customer.check_phone(customer_phone):
            return customer_phone
        else:
            print("电话格式等不正确，使用默认的")
        return "None"

    # ----------------------------------------------添加客户, email 校验-----------------------------------------------------------

    def set_customer_email(self):
        customer_email = input("请输入你的邮箱：")
        if Customer.check_email(customer_email):
            return customer_email
        else:
            print("邮箱非法 ，使用默认的")
        return "None"

    # -----------------------------------------------end----------------------------------------------------------------------------
    # ----------------------------------------------------------------------------------------------------------------------------

    def add_customer(self):
        """添加客户"""
        if not (customer_id := self.set_customer_id()):  # 添加客户id
            return
        if not (customer_name := self.set_customer_name()):  # 添加客户name
            return

        customer_age = self.set_customer_age()  # 添加客户age
        customer_phone = self.set_customer_phone()  # 添加客户电话
        customer_email = self.set_customer_email()  # 添加客户邮箱

        # 客户的几个 信息都给添加到客户对象里
        customer = Customer(customer_id, customer_name, customer_age, customer_phone, customer_email)
        # 再将客户对象添加到字典里  ，有两个字典
        self.customer_id_dict[customer_id] = customer  # id字典，根据id,添加客户信息

        customer_inner_dict = self.customer_name_dict.get(
            customer_name)  # name字典，里的嵌套字典 k:name v(k:id v:customer),#本行代码 是根据字典的名字获取到的内层嵌套的字典 v(k:id v:customer)
        if customer_inner_dict is None:
            self.customer_name_dict[customer_name] = {customer_id: customer}
        else:
            customer_inner_dict[customer_id] = customer
        print(f"添加客户{customer_id}成功")

    # -----------------------------------------------添加客户----end-----------------------------------------------------------------------------

    def delete_customer(self):
        """删除客户"""
        # 1，获取客户id
        customer_id = input("请输入要删除的客户id:")
        # 2, 检查id 是否合法
        if not Customer.check_c_id(customer_id):
            print("客户id必须是纯数字，终止删除客户")
            return
        # 3, 删除id
        if customer_id not in self.customer_id_dict:
            print("客户id不存在，终止删除")
            return
        else:

            # 从名字字典里 根据k:id获取客户名字，
            customer_name = self.customer_id_dict[customer_id].name  # 根据客户id字典的 k:id ,获取到k:name,这个name 就是客户name字典的k
            # 删除客户id字典里的数据，根据 k:id 删除
            del self.customer_id_dict[customer_id]

            customer_inner_dict = self.customer_name_dict.get(customer_name)  # 根据名字字典的 k:name 获取到名字字典里的内嵌字典
            if customer_inner_dict is not None:
                del customer_inner_dict[customer_id] #从内嵌字典中删除对应ID的记录
                #如果内嵌字典为空，则删除整个名字对应的键值对 就是删除的对应的客户名字字典
            if len(customer_inner_dict) == 0:
                del self.customer_name_dict[customer_name]

            print("删除客户完成.....")

    def update_customer(self):
        """"修改客户信息"""
        # 1,获取客户id,
        customer_id = input("请输入要添加的客户id:")
        # 2,检查id 是否合法
        if not Customer.check_c_id(customer_id):
            print("客户id必须是纯数字，终止添加客户")
            return
        # 3，更新客户
        if customer_id not in self.customer_id_dict:
            print("客户id不存在，终止更新客户信息")
            return
        else:
            # 3.1更新客户年龄
            print(f"客户{customer_id}未修改之前的年龄:{self.customer_id_dict[customer_id].age}")  # 根据客户id字典里的k:id获取到age
        customer_age = self.set_customer_age()  # 调用输入客户年龄的方法 获取到customer_age
        # 检查获取到的 customer_age 是否是"None"
        if customer_age  is not None:
            self.customer_id_dict[customer_id].age = customer_age
        # 3.2更新客户电话
        print(f"客户{customer_id}未修改之前的电话:{self.customer_id_dict[customer_id].phone}")
        # customer_phone = self.set_customer_phone()
        # if customer_phone != None:
        #     self.customer_id_dict[customer_id].phone = customer_phone
        # 等同于
        if (customer_phone := self.set_customer_phone()) is not None:
            self.customer_id_dict[customer_id].phone = customer_phone

        #3.3 更新客户邮箱
        print(f"客户{customer_id}未修改之前的邮箱:{self.customer_id_dict[customer_id].email}")
        if (customer_email := self.set_customer_email())  is not None:
            self.customer_id_dict[customer_id].email = customer_email
        print(f"客户{customer_id}的信息修改成功了....")

    def search_customer(self):
        """查询客户信息"""
        # 1,获取客户id或名字,
        customer_info = input("请输入要查询的客户id或名字:")
        # 2,分别 检查id和名字是否合法
        # 2.1,检查id 是否合法
        if Customer.check_c_id(customer_info):
            if customer_info not in self.customer_id_dict:
                print("客户id不存在")
            else:
                print(self.customer_id_dict[customer_info])#自动调用__str__方法
        elif Customer.check_name(customer_info):
            if customer_info in self.customer_name_dict:
                for i in self.customer_name_dict[customer_info]:
                    print(self.customer_name_dict[customer_info][i])
            else:
                print("客户名字不存在")
        else:
            print("输入的不是id和名字")

    def display_customer(self):
        """显示所有客户信息"""
        if len(self.customer_id_dict) == 0:
            print("暂无客户信息")
            return
        else:
            for k in self.customer_id_dict.keys():
                print(self.customer_id_dict[k]) #自动调用__str__方法

    def display_menu(self):
        """显示菜单"""
        print("""----------------------------------------------客户管理系统------------------------
                                    1.添加客户
                                    2.删除客户
                                    3.修改客户
                                    4.查询客户
                                    5.显示客户
                                    6.退出
                    """)

    def start_menu(self):
        """启动菜单"""
        try:
            while True:
                self.display_menu()
                match input("请输入你想要的操作："):
                    case "1":
                        print("添加客户")
                        self.add_customer()
                    case "2":
                        print("删除客户")
                        self.delete_customer()
                    case "3":
                        print("修改客户")
                        self.update_customer()
                    case "4":
                        print("查询客户")
                        self.search_customer()
                    case "5":
                        print("显示客户")
                        self.display_customer()
                    case "6":
                        print("退出系统")
                        time.sleep(0.1)
                    case _:
                        print("输入有误，请重新输入：")

        except Exception as e:
            print(e)


if __name__ == "__main__":
    c = CMS()
    c.start_menu()
